<template>
  <div class="page">
    <h2>智力/发育障碍与支持</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/档案号/诊断搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="diagnosisFilter" placeholder="诊断" style="width:180px">
        <el-option label="全部" :value="''" />
        <el-option label="自闭谱系(ASD)" value="ASD" />
        <el-option label="智力障碍(ID)" value="ID" />
        <el-option label="发育迟缓" value="DD" />
      </el-select>

      <el-select v-model="iepFilter" placeholder="是否有IEP" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="有IEP" value="yes" />
        <el-option label="无IEP" value="no" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增档案</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="recordId" label="档案号" width="140" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="diagnosis" label="诊断" width="160" />
      <el-table-column prop="iep" label="IEP" width="100" />
      <el-table-column prop="carePlan" label="康复/教育计划" />
      <el-table-column prop="assigned" label="责任医师/康复师" width="160" />

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.recordId)">编辑</el-button>
          <el-button size="small" @click="openIEP(row.recordId)" style="margin-left:8px">管理IEP</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.recordId)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchOpenIEP">批量标记IEP</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑档案' : '新增档案'" v-model="showModal" width="700px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="档案号"><el-input v-model="form.recordId" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="年龄/性别">
          <div style="display:flex;gap:8px">
            <el-input-number v-model="form.age" :min="0" style="width:120px" />
            <el-select v-model="form.gender" style="width:120px"><el-option label="男" value="M" /><el-option label="女" value="F" /></el-select>
          </div>
        </el-form-item>
        <el-form-item label="诊断">
          <el-select v-model="form.diagnosis" style="width:260px">
            <el-option label="自闭谱系(ASD)" value="ASD" />
            <el-option label="智力障碍(ID)" value="ID" />
            <el-option label="发育迟缓(DD)" value="DD" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有IEP"><el-select v-model="form.iep" style="width:120px"><el-option label="是" value="yes" /><el-option label="否" value="no" /></el-select></el-form-item>
        <el-form-item label="康复/教育计划"><el-input v-model="form.carePlan" /></el-form-item>
        <el-form-item label="家庭培训记录"><el-input v-model="form.familyTraining" /></el-form-item>
        <el-form-item label="责任医师/康复师"><el-input v-model="form.assigned" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { recordId: 'D001', name: '小华', age: 6, gender: 'M', diagnosis: 'ASD', iep: 'yes', carePlan: '言语+行为干预', familyTraining: '家长训练1次', assigned: '张康复师' },
  { recordId: 'D002', name: '小丽', age: 10, gender: 'F', diagnosis: 'ID', iep: 'no', carePlan: '学校适应/特殊教育', familyTraining: '', assigned: '李医生' }
];

const data = ref([]);
const q = ref('');
const diagnosisFilter = ref('');
const iepFilter = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ recordId:'', name:'', age:0, gender:'M', diagnosis:'ASD', iep:'no', carePlan:'', familyTraining:'', assigned:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || String(d.recordId).toLowerCase().includes(qq) || (d.diagnosis||'').toLowerCase().includes(qq))) return false;
    if(diagnosisFilter.value && d.diagnosis !== diagnosisFilter.value) return false;
    if(iepFilter.value){ if(iepFilter.value==='yes' && d.iep!=='yes') return false; if(iepFilter.value==='no' && d.iep!=='no') return false; }
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.recordId); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.recordId===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{recordId:'',name:'',age:0,gender:'M',diagnosis:'ASD',iep:'no',carePlan:'',familyTraining:'',assigned:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.recordId || !form.name){ ElMessage.warning('档案号和姓名为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.recordId===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ data.value.push(JSON.parse(JSON.stringify(form))); }
  showModal.value=false; ElMessage.success('保存成功'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该档案？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.recordId!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function openIEP(id){ ElMessage.info('打开IEP管理（示例）: ' + id); }
function batchOpenIEP(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessage.success('已为所选标记IEP（示例）'); }
function batchDelete(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条档案？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.recordId)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['recordId','name','age','gender','diagnosis','iep','carePlan','familyTraining','assigned'], ...data.value.map(d=>[d.recordId,d.name,d.age,d.gender,d.diagnosis,d.iep,d.carePlan||'',d.familyTraining||'',d.assigned||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='developmental.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>